package com.cndcare.msc.handler;

import com.cndcare.msc.components.ChannelRepository;
import com.cndcare.msc.protobuf.CmdEnum;
import com.cndcare.msc.protobuf.MessageVo;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.AttributeKey;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 其他业务拓展模板参考
 */
@Component(value = "otherServerHandler")
@ChannelHandler.Sharable
public class OtherServerHandler extends ChannelInboundHandlerAdapter {
    public Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("channelRepository")
    private ChannelRepository channelRepository;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MessageVo messageVo = (MessageVo) msg;
        log.info(messageVo.getData());
        ChannelFuture cf = ctx.writeAndFlush(
                MessageVo.builder()
                        .mac(messageVo.getMac())
                        .cmdEnum(CmdEnum.UPLOAD_DATA_BACK)
                        .data("自动回复：服务器收到消息 - " + messageVo.getData())
                        .build()
        );
        /* 上一条消息发送成功后，立马推送一条消息 */
        cf.addListener(future -> {
            if (future.isSuccess()) {
                ctx.writeAndFlush(
                        MessageVo.builder()
                                .mac(messageVo.getMac())
                                .cmdEnum(CmdEnum.PUSH_DATA)
                                .data("开始发送业务数据了。。。")
                                .build()
                );
            }
        });
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }


}
